package com.offcn.user.service.impl;

import com.offcn.user.exception.UserExistException;
import com.offcn.user.mapper.TMemberAddressMapper;
import com.offcn.user.mapper.TMemberMapper;
import com.offcn.user.pojo.TMember;
import com.offcn.user.pojo.TMemberAddress;
import com.offcn.user.pojo.TMemberAddressExample;
import com.offcn.user.pojo.TMemberExample;
import com.offcn.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired(required = false)
    private TMemberMapper tMemberMapper;

    @Autowired(required = false)
    private TMemberAddressMapper addressMapper;

    @Override
    public void registerUser(TMember member) {
        // 查询当前手机号是否已经注册
        TMemberExample example = new TMemberExample();
        TMemberExample.Criteria criteria = example.createCriteria();
        criteria.andLoginacctEqualTo(member.getLoginacct());
        List<TMember> tMembers = tMemberMapper.selectByExample(example);
        if(tMembers != null && tMembers.size() > 0){
            // 抛个异常
            throw new UserExistException();
        }
        // 密码加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String pwd = encoder.encode(member.getUserpswd());
        member.setUserpswd(pwd);
        // 未认证
        member.setAuthstatus("0");
        // 个人类型的用户
        member.setUsertype("0");
        // 个人账户
        member.setAccttype("2");
        tMemberMapper.insert(member);
    }

    @Override
    public TMember login(String loginacct, String userpswd) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        // 通过手机号获取用户信息
        TMemberExample example = new TMemberExample();
        TMemberExample.Criteria criteria = example.createCriteria();
        criteria.andLoginacctEqualTo(loginacct);
        List<TMember> members = tMemberMapper.selectByExample(example);
        if(members != null && members.size() == 1 ){
            TMember tMember = members.get(0);
            // 密码匹配
            // matches(没有加密的字符串，加密以后的字符串)
            boolean matches = encoder.matches(userpswd, tMember.getUserpswd());
            return matches?tMember:null;
        }
        return null;
    }

    @Override
    public TMember getTMemberById(Integer id) {
        return tMemberMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<TMemberAddress> getAddresList(Integer memberId) {
        TMemberAddressExample example = new TMemberAddressExample();
        TMemberAddressExample.Criteria criteria = example.createCriteria();
        criteria.andMemberidEqualTo(memberId);
        return addressMapper.selectByExample(example);
    }
}
